// Copyright 2013 The Go Circuit Project
// Use of this source code is governed by the license for
// The Go Circuit Project, found in the LICENSE file.
//
// Authors:
//   2013 Petar Maymounkov <p@gocircuit.org>

package focus

import (
	"net"

	"circuit/kit/rh"
	"circuit/kit/rh/ns"
)

// cluster is a namespace of type ns.MapDir listing all circuit hosts.
type cluster loci

func newCluster(peer *Peer, peers PeerFunc, shutter rh.FID) *cluster {
	return (*cluster)(newLoci(peer, peers, shutter))
}

func (c *cluster) Map() map[string]ns.Dir { // If Map panics, the panic will be reported as ErrIO to RH, and subsequently syscall.EIO to FUSE.
	bulk := c.peers()
	dir := make(map[string]ns.Dir)
	for _, peer := range bulk {
		hname := hostfrom(peer.Kin.X.Addr().NetAddr())
		//
		d, ok := dir[hname]
		if !ok {
			d = newHost(c.peer, c.shutter)
			dir[hname] = d
		}
		h := d.(*host)
		h.peers = append(h.peers, peer)
	}
	return dir
}

func hostfrom(na net.Addr) string {
	var src = []byte(na.(*net.TCPAddr).IP.String())
	// for i, b := range src {
	// 	switch b {
	// 	case ':', '/', '"', '(', ')':
	// 		src[i] = '_'
	// 	}
	// }
	return string(src)
}

// host
type host struct {
	*loci
	peers []*Peer
}

func newHost(peer *Peer, shutter rh.FID) *host {
	h := &host{}
	h.loci = newLoci(peer, func() []*Peer {
		return h.peers
	}, shutter)
	return h
}
